package org.anti996.lms.util;


import org.apache.commons.lang.StringUtils;
import org.apache.tomcat.util.http.fileupload.impl.FileSizeLimitExceededException;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

/**
 * 文件上传工具类
 *
 * @author ruoyi
 */
public final class FileUploadUtils {

    /**
     * 默认大小 50M
     */
    public static final long DEFAULT_MAX_SIZE = 50 * 1024 * 1024;

    /**
     * 默认的文件名最大长度 100
     */
    public static final int DEFAULT_FILE_NAME_LENGTH = 100;

    /**
     * 默认上传的地址
     */
    private static String defaultBaseDir = "./uploadPath";
    public static final String RESOURCE_PREFIX = "/profile";

    public static void setDefaultBaseDir(String defaultBaseDir) {
        FileUploadUtils.defaultBaseDir = defaultBaseDir;
    }

    public static String getDefaultBaseDir() {
        return defaultBaseDir;
    }

    /**
     * 以默认配置进行文件上传
     *
     * @param file 上传的文件
     * @return 文件名称
     * @throws Exception
     */
    public static String upload(MultipartFile file) throws IOException {
        try {
            return upload(getDefaultBaseDir(), file);
        } catch (Exception e) {
            throw new IOException(e.getMessage(), e);
        }
    }


    /**
     * 文件上传
     *
     * @param baseDir 相对应用的基目录
     * @param file    上传的文件
     * @return 返回上传成功的文件名
     * @throws FileSizeLimitExceededException 如果超出最大大小
     * @throws IOException                    比如读写文件出错时
     */
    public static String upload(String baseDir, MultipartFile file)
            throws Exception {
        int fileNamelength = file.getOriginalFilename().length();
        if (fileNamelength > FileUploadUtils.DEFAULT_FILE_NAME_LENGTH) {
            throw new Exception();
        }

        assertAllowed(file);

        String fileName = extractFilename(file);

        String desc = getAbsoluteFile(baseDir, fileName);
//        file.transferTo(desc);
        Path destinationFile = Path.of(desc);
        Files.copy(file.getInputStream(), destinationFile);
        return getPathFileName(baseDir, fileName);
    }

    /**
     * 编码文件名
     */
    public static String extractFilename(MultipartFile file) {
        String fileName;
        String extension = getExtension(file);
        fileName = System.currentTimeMillis() + "." + extension;
        return fileName;
    }

    public static String getAbsoluteFile(String uploadDir, String fileName) throws IOException {
        String path = uploadDir + File.separator + fileName;
        File desc = new File(path);

        if (!desc.getParentFile().exists())
        {
            desc.getParentFile().mkdirs();
        }
        return path;
    }

    public static String getPathFileName(String uploadDir, String fileName) throws IOException {
        int dirLastIndex = "./uploadPath".length() + 1;
        String currentDir = StringUtils.substring(uploadDir, dirLastIndex);
//        String pathFileName = RESOURCE_PREFIX + "/" + currentDir + "/" + fileName;
        String pathFileName = RESOURCE_PREFIX + "/" + fileName;
        return pathFileName;
    }

    /**
     * 文件大小校验
     *
     * @param file 上传的文件
     * @return
     * @throws FileSizeLimitExceededException 如果超出最大大小
     */
    public static void assertAllowed(MultipartFile file)
            throws Exception {
        long size = file.getSize();
        if (DEFAULT_MAX_SIZE != -1 && size > DEFAULT_MAX_SIZE) {
            throw new Exception();
        }

        String fileName = file.getOriginalFilename();

    }

    /**
     * 获取文件名的后缀
     *
     * @param file 表单文件
     * @return 后缀名
     */
    public static String getExtension(MultipartFile file) {
        if (file == null) return null;
        String filename = file.getOriginalFilename();
        // split用的是正则，所以需要用 //. 来做分隔符
        String[] split = filename.split("\\.");
        //注意判断截取后的数组长度，数组最后一个元素是后缀名
        if (split.length > 1) {
            return split[split.length - 1];
        } else {
            return "";
        }
    }

}
